package com.csl.jsonpreference.ui

import android.annotation.SuppressLint
import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.text.TextUtils
import android.view.LayoutInflater
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.fragment.app.Fragment
import com.csl.jsonpreference.R
import com.csl.jsonpreference.bean.ConfigTYPE
import com.csl.jsonpreference.configdes.JsonArrayPreference
import com.csl.jsonpreference.configdes.JsonConfigIns
import com.csl.jsonpreference.configdes.JsonObjectPreference
import com.csl.jsonpreference.databinding.ActivityJsonpreferenceBinding
import com.csl.jsonpreference.tag.JsonConfig
import com.csl.jsonpreference.util.CLog
import org.json.JSONObject

class JsonPreferenceActivity : AppCompatActivity() {
    companion object {
        final val PARAM_JSON = "config_data"
        final val PARAM_TITLE = "config_title"
        final val PARAM_CLASS = "config_class"
        final val RESULT_JSON = "result_json"
        val CODE_RESULT_SUCCESS = Activity.RESULT_OK
        val CODE_RESULT_FAIL = 500
        val CODE_RESULT_CANCEL = Activity.RESULT_CANCELED
    }


    var viewBinding: ActivityJsonpreferenceBinding? = null;

    var rootFragment: JsonPreferenceFragment = JsonPreferenceFragment()
    var fragmentListener = object : OnOpenOrCloseListener {
        override fun onGroupOpen(group: JsonObjectPreference) {
            var fragment = JsonPreferenceFragment()
            fragment.onOpenOrCloseListener = this
            fragment.configData = group
            showFragment(fragment, "${group.title}")
        }

        override fun onArrayOpen(array: JsonArrayPreference) {
            var fragment = JsonArrayFragment()
            fragment.onOpenOrCloseListener = this
            fragment.configData = array
            showFragment(fragment, "${array.title}")
        }

        override fun onClose() {
        }

    }

    @SuppressLint("RestrictedApi")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        viewBinding = ActivityJsonpreferenceBinding.inflate(LayoutInflater.from(this))
        setContentView(viewBinding!!.root)

        supportActionBar?.setDefaultDisplayHomeAsUpEnabled(true)


//        var obj = WifiDeviceConfig()
//        var group = Config2Object.toPreference(obj)
//        var jsonStr = Gson().toJson(group)
//        rootFragment.configData = Config2Object.toPreference(obj)

        var objJson = intent.getStringExtra(PARAM_JSON)
        var clazz: Class<*>? = intent.getSerializableExtra(PARAM_CLASS) as Class<*>?
        if (objJson == null) {
            Toast.makeText(this, "配置信息错误", Toast.LENGTH_SHORT).show()
            finish()
            return
        }
        var title = intent.getStringExtra(PARAM_TITLE)

        CLog.d("json", "获取到的配置:$objJson, 目标类型:$clazz")
        var jsonObject = try {
            JSONObject(objJson)
        } catch (e: Exception) {
            e.printStackTrace()
            JSONObject()
        }

        var jsonConfig = JsonConfigIns(clazz?.getAnnotation(JsonConfig::class.java))
        jsonConfig.configType = ConfigTYPE.AUTO
        if(!TextUtils.isEmpty(title)) {
            jsonConfig.title = title!!
        }

        var jsonRoot = JsonObjectPreference(
            jsonObject,
            clazz,
            jsonConfig
        )

        rootFragment.configData = jsonRoot


        showFragment(rootFragment, "${rootFragment.configData!!.title}")

        rootFragment.onOpenOrCloseListener = fragmentListener

        setResult(CODE_RESULT_FAIL)
    }


    override fun onDestroy() {
        super.onDestroy()
        viewBinding = null
        rootFragment.configData?.let {
//            var obj = AquaDeviceConfig()
//            Config2Object.toObject(it, obj);
//
//            CLog.d("test_json", "end json: ${Gson().toJson(obj)}")
        }
    }

    fun showToast(str: String) {
        runOnUiThread {
            Toast.makeText(this, "$str", Toast.LENGTH_SHORT).show()
        }
    }

    fun showFragment(fragment: Fragment, title: String) {
        this.title = title
        supportFragmentManager.beginTransaction().replace(R.id.fl_container, fragment).commit()
    }

    override fun onBackPressed() {
        if (rootFragment.isResumed) {
//            super.onBackPressed()
            rootFragment.configData?.let {
//                var ddd = Gson().toJson(it.jsonData)
                var resultIntent = Intent().apply {
                    putExtra(RESULT_JSON, it.jsonData.toString())
                }

                setResult(CODE_RESULT_SUCCESS, resultIntent)
                super.onBackPressed()
//
//                //转OBJ
//                var obj = WifiDeviceConfig()
//                Config2Object.toObject(it, obj)
//                CLog.d("test_json", "target json: ${Gson().toJson(obj)}")
//
//
//
//
//                var decode = GroupPreference().apply {
//                    setForJson(JSONObject(ddd))
//                }
////                CLog.d("test_json", "dec json: ${Gson().toJson(decode)}")
//
//                var obj2 = WifiDeviceConfig()
//                Config2Object.toObject(decode, obj2)
//                CLog.d("test_json", "end json: ${Gson().toJson(obj2)}")

            }
        } else {
            showFragment(rootFragment, "${rootFragment.configData!!.title}")
        }
    }


}